package com.tourism.util;

import com.tourism.entity.User;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;

/**
 * @Description
 * @Author z
 * @Date 2021-03-08 22:18
 */
@Component
public class JwtTokenUtil {


    @Value("${jwt.secret}")
    private String secret = "tourism";

    @Value("${jwt.expire.second}")
    private long expireTime;

    /**
     * 从token中获取用户名
     *
     * @param token
     * @return
     */
    public String getUsernameFromToken(String token) {
        return getClaimFromToken(token, Claims::getSubject);
    }

    /**
     * 从token中获取用户id
     *
     * @param token
     * @return
     */
    public Long getUserIdFromToken(String token) {
        return Long.valueOf(getClaimFromToken(token, Claims::getId));
    }

    /**
     * 获取token的过期时间
     *
     * @param token
     * @return
     */
    public Date getExpirationDateFromToken(String token) {
        return getClaimFromToken(token, Claims::getExpiration);
    }

    public <T> T getClaimFromToken(String token, Function<Claims, T> claimsResolver) {
        final Claims claims = getAllClaimsFromToken(token);
        return claimsResolver.apply(claims);
    }

    /**
     * 从token中获取所有相关信息
     *
     * @param token
     * @return
     */
    private Claims getAllClaimsFromToken(String token) {
        return Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();
    }

    /**
     * 验证这个token是否过期
     *
     * @param token
     * @return
     */
    private Boolean isTokenExpired(String token) {
        final Date expiration = getExpirationDateFromToken(token);
        return expiration.before(new Date());
    }

    /**
     * 根据用户生成一个token
     *
     * @param user
     * @return
     */
    public String generateToken(User user) {
        Map<String, Object> claims = new HashMap<>();
        return doGenerateToken(claims, user);
    }

    /**
     * 生成token的方法
     *
     * @param claims
     * @param user
     * @return
     */
    private String doGenerateToken(Map<String, Object> claims, User user) {

        return Jwts.builder().setClaims(claims).setSubject(user.getUsername()).setId(user.getId().toString()).
                setIssuedAt(new Date(System.currentTimeMillis()))
                .setExpiration(new Date(System.currentTimeMillis() + expireTime * 1000))
                .signWith(SignatureAlgorithm.HS512, secret).compact();
    }

    /**
     * 验证toker
     *
     * @param token
     * @param user
     * @return
     */
    public Boolean validateToken(String token, User user) {
        final Long userId = getUserIdFromToken(token);
        return (userId.equals(user.getId()) && !isTokenExpired(token));
    }

    public static void main(String[] args) {
        User user = new User();
        user.setUsername("张三");
        JwtTokenUtil jwtTokenUtil = new JwtTokenUtil();
        String token = jwtTokenUtil.generateToken(user);
        System.out.println(jwtTokenUtil.getExpirationDateFromToken(token));
        String tk = "eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiLlvKDkuIkiLCJleHAiOjE2MTUyMzIxOTYsImlhdCI6MTYxNTIxNDE5Nn0.ueHtpjtz11tVzXiSSI8XKgSkAGLE6EIb2Vl8AuPAIlwEIeA9ADB1FLZ16a9FgGrAgz9JRwHq6WASdbkk0eNWgA";
        System.out.println(jwtTokenUtil.isTokenExpired(tk));
        System.out.println(jwtTokenUtil.getUsernameFromToken(tk));
        System.out.println(token);
    }
}
